import { EleMessage } from "ele-admin-plus/es";

// 新增公共类型检查方法
export function checkAndHandleResult(result) {
  console.log(result, "result");

  if (result instanceof Promise) {
    return result
      .then((res) => {
        console.log("Promise resolved:", res);
        return res;
      })
      .catch((e) => {
        console.error("Promise rejected:", e);
        return Promise.reject(e);
      });
  }

  if (result instanceof Error) {
    console.error("Returned Error:", result);
    return Promise.reject(result);
  }

  if (result === false) {
    const err = new Error("操作已被钩子终止");
    console.warn(err.message);
    return Promise.reject(err);
  }

  return Promise.resolve(result);
}

export function useSubmitHook() {
  const handleBeforeSubmit = (config, params) => {
    try {
      if (config?.beforeSubmit) {
        const result = config.beforeSubmit(params);
        return checkAndHandleResult(result);
      }
      return Promise.resolve(params);
    } catch (error) {
      console.error("同步错误:", error);
      return Promise.reject(error);
    }
  };

  const handleAfterSubmit = (config, result) => {
    if (config?.afterSubmit) {
      return Promise.resolve()
        .then(() => {
          const res = config.afterSubmit(result);
          return res instanceof Promise ? res : Promise.resolve();
        })
        .catch((e) => {
          console.error("afterSubmit钩子执行出错:", e);
        });
    }
    return Promise.resolve();
  };

  const handleSubmitError = (config, error) => {
    if (config?.onSubmitError) {
      try {
        const result = config.onSubmitError(error);
        if (result instanceof Promise) {
          result.catch((err) =>
            console.error("onSubmitError钩子执行出错:", err),
          );
        }
      } catch (err) {
        console.error("onSubmitError钩子执行出错:", err);
      }
    }
    console.log(config, error, typeof error, "error11");
    // EleMessage.error(error.message);
  };

  return {
    handleBeforeSubmit,
    handleAfterSubmit,
    handleSubmitError,
  };
}
